/*
 *  QMText.h
 *  QuickMatch
 *
 *  Created by Leroy Ketelaars on 8/13/09.
 *  Copyright 2009 Universum7. All rights reserved.
 *
 */

#ifndef __QM_TEXT_H__
#define __QM_TEXT_H__

#include <iostream>
#include <string>
#include "SDL.h"
#include "SDL_ttf/SDL_ttf.h"

using namespace std;

class QMText
{
public:
	string			name;
	SDL_Surface		*render,
					*shadow;
	bool			rerender_required,
					uses_shadow,
					uses_borrowedfont;
	TTF_Font*		font;
	SDL_Color		color,
					shade;
	Uint8			shade_alpha;
	int				size;
	
	//constructor with arguments, could be handy
	QMText(string text, int fsize, string fontpath, bool useshadows, Uint8 r, Uint8 g, Uint8 b): render(NULL), shadow(NULL), uses_borrowedfont(false), rerender_required(false), uses_shadow(true), shade_alpha(128)
	{
		color.r = r; color.g = g; color.b = b;
		shade.r = shade.g = shade.b = 0;
		name = text;
		size = fsize;
		font = TTF_OpenFont(fontpath.c_str(), fsize);
	}
	//default constructor, doesn't open any fonts or anything, allows you to use existing TTF_Font pointers
	//instead of loading another one, if you want to do so
	QMText(): render(NULL), shadow(NULL), rerender_required(false), uses_shadow(true), shade_alpha(128), uses_borrowedfont(false)
	{
		shade.r = shade.g = shade.b = 0;
		name = "Player";
		size = 12;
		color.r = color.g = color.b = 0xff;
	}
	~QMText()
	{
		printf("QMText: Deleting instance @ %p\n", this);
		if(render != NULL) 
		{
			SDL_FreeSurface(render);
			render = NULL;
		}
		if(shadow != NULL)
		{
			SDL_FreeSurface(shadow);
			shadow = NULL;
		}
		if(uses_borrowedfont == false)
		{
			if(font != NULL)
			{
				printf("\tclosing and deleting font\n");
				TTF_CloseFont(font);
				font = NULL;
			}
		}
	}
	void update()
	{
		if(rerender_required)
		{
			rerender_required = false;
			render = TTF_RenderText_Blended(font, name.c_str(), color);
			if(uses_shadow)
			{
				shadow = TTF_RenderText_Blended(font, name.c_str(), shade);
				SDL_SetAlpha(shadow, shade_alpha, SDL_RLEACCEL | SDL_SRCALPHA);
			}
		}
	}
	void setText(string text)
	{
		name = text;
		rerender_required = true;
		update();
	}
	void setSize(int fsize)
	{
		size = fsize;
		rerender_required = true;
		update();
	}
	void setShadeAlpha(Uint8 alp)
	{
		if(uses_shadow)
		{
			shade_alpha = alp;
			SDL_SetAlpha(shadow, shade_alpha, SDL_RLEACCEL | SDL_SRCALPHA);
		}
	}
	void borrowFont(TTF_Font* fon)
	{
		font = fon;
		uses_borrowedfont = true;
	}
};

#endif
